#include "../inc/Ui/TwitterMyFollowingForm.h"
#include "../inc/Model/TwitterMySnsGatewayManager.h"
#include "../inc/Ui/TwitterForm.h"
#include "../inc/Ui/WebForm.h"
#include <FApp.h>

using namespace Osp::Base;
using namespace Osp::App;
using namespace Osp::Base::Collection;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;
using namespace Osp::Media;
using namespace Osp::Graphics;
using namespace Osp::Social;
using namespace Osp::Social::Services;
int MyFollowingForm::FormId = -1;
MyFollowingForm::MyFollowingForm(void) {
}

MyFollowingForm::~MyFollowingForm(void) {
}

bool MyFollowingForm::Initialize() {
	Form::Construct(L"Twitter_FollowingListForm");

	return true;
}

result MyFollowingForm::OnInitializing(void) {
	result r = E_SUCCESS;
	__pPicturesCache.Construct();
	Application *pApp = Application::GetInstance();
	// TODO: Add your initialization code here
	this->SetSoftkeyActionId(SOFTKEY_0, ID_SOFTKEY_SHOWMAP);
	this->AddSoftkeyActionListener(SOFTKEY_0, *this);
	this->SetSoftkeyActionId(SOFTKEY_1, ID_SOFTKEY_BACK);
	this->AddSoftkeyActionListener(SOFTKEY_1, *this);

	pOptionMenu = new OptionMenu();
	pOptionMenu->Construct();
	String temp;
	pApp->GetAppResource()->GetString("IDS_FOLLOWING_REPLY", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_REPLY);

	pApp->GetAppResource()->GetString("IDS_FOLLOWING_USERPROFILE", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_USERPROFILE);

	pOptionMenu->AddItem("Xem Map", ID_SOFTKEY_XEMFRIENDINMAP);
	SetOptionkeyActionId(ID_OPTIONMENU);
	AddOptionkeyActionListener(*this);
	pOptionMenu->AddActionEventListener(*this);

	__pFollowerList = static_cast<List*> (GetControl("IDC_LIST1"));
	__pFollowerList->AddItemEventListener(*this);

	this->SetSoftkeyActionId(SOFTKEY_1, ID_SOFTKEY_BACK);
	this->AddSoftkeyActionListener(SOFTKEY_1, *this);

	pButtonNext = static_cast<Button *> (GetControl("IDC_BUTTON_NEXT"));
	pButtonNext->SetActionId(ID_BUTTON_NEXT);
	pButtonNext->AddActionEventListener(*this);
	pButtonHome = static_cast<Button*> (GetControl("IDC_BUTTON_HOME"));
	pButtonHome->SetActionId(ID_BUTTON_HOME);
	pButtonHome->AddActionEventListener(*this);

	// Create Bitmaps
	Bitmap* pBitmapNext = GetBitmapN("next.jpg");
	Bitmap* pBitmapHome = GetBitmapN("home.jpg");
	Bitmap* pBitmapNextPress = GetBitmapN("nextpress.jpg");
	Bitmap* pBitmapHomePress = GetBitmapN("homepress.jpg");

	// Set Bitmaps to the bitmap Button.
	//AppLog("Vao button add image");
	pButtonNext->SetNormalBackgroundBitmap(*pBitmapNext);
	pButtonNext->SetPressedBackgroundBitmap(*pBitmapNextPress);
	pButtonHome->SetNormalBackgroundBitmap(*pBitmapHome);
	pButtonHome->SetPressedBackgroundBitmap(*pBitmapHomePress);

	//	AppLog("KetThus");
	// Deallocate Bitmaps
	delete pBitmapNext;
	delete pBitmapHome;
	SetStateToButton(false, false, false, false);
	return r;
}

result MyFollowingForm::OnTerminating(void) {
	result r = E_SUCCESS;

	// TODO: Add your termination code here

	return r;
}
void MyFollowingForm::SetStateToButton(bool home, bool next, bool statOption,
		bool showMap) {
	pButtonHome->SetEnabled(home);
	pButtonNext->SetEnabled(next);
	IsOpenedOptionMenu = statOption;
	this->SetSoftkeyEnabled(SOFTKEY_0, showMap);
}
void MyFollowingForm::OnActionPerformed(const Osp::Ui::Control& source,
		int actionId) {
	FormManager *pFormManager = null;
	Form *pTwitterForm = null;
	Form *pReplyForm = null;
	Form *pWebForm = null;
	FormManager::GetInstance(pFormManager);
	pFormManager->GetForm(TwitterForm::GetFormId(), pTwitterForm);
	pFormManager->GetForm(TwitterReplyForm::GetFormId(), pReplyForm);
	pFormManager->GetForm(WebForm::GetFormId(), pWebForm);
	MySnsGatewayManager
			*pMySnsGatewayManager =
					(static_cast<TwitterForm*> (pTwitterForm))->GetSnsGatewayTwitterForm();
	switch (actionId) {
	case ID_BUTTON_HOME: {
		//	AppLog("Home");
		SetStateToButton(false, false, false, false);
		bool kq = pMySnsGatewayManager->RequestHomeFriends();
		if (kq == false) {
			AppLog("Ket qua=false");
			SetStateToButton(true, true, true, true);
			//pButtonNext->SetEnabled(true);
			//pButtonHome->SetEnabled(true);
		}
	}
		break;
	case ID_BUTTON_NEXT: {
		//	AppLog("Next");
		SetStateToButton(false, false, false, false);
		bool kq = pMySnsGatewayManager->RequesrMoreFriends();
		if (kq == false) {
			SetStateToButton(true, true, true, true);
			//	AppLog("Ket qua=false");
			//pButtonNext->SetEnabled(true);
			//pButtonHome->SetEnabled(true);
		}
	}
		break;
	case ID_OPTIONMENU: {
		if (IsOpenedOptionMenu == true) {
			AppLog("Option Menu mo dc");
			pOptionMenu->SetShowState(true);
			pOptionMenu->Show();
		}
		AppLog("OptionMenu khong mo dc");
	}
		break;
	case ID_OPTIONMENU_REPLY: {
		SnsProfile *pUserSnsProfile =
				pMySnsGatewayManager->GetSnsProfileByIndex(indexSelectedInList);

		if (pUserSnsProfile == null) {
			return;
		} else {
			String userName;
			pUserSnsProfile->GetValue(SNS_PROFILE_PID_DISPLAY_NAME, userName);

			(static_cast<TwitterReplyForm*> (pReplyForm))->UpdateInfomationOfUserName(
					userName);
			pFormManager->SetCurrentForm(TwitterReplyForm::GetFormId());
		}
	}
		break;
	case ID_OPTIONMENU_USERPROFILE:
		pMySnsGatewayManager->RequestProfileFollowingByIndex(
				indexSelectedInList);
		pFormManager->SetCurrentForm(TwitterUsernameProfileForm::GetFormId());
		break;

	case ID_SOFTKEY_SHOWMAP: {//Show location of friend in map
		pFormManager->SetCurrentForm(WebForm::GetFormId());
		(static_cast<WebForm*> (pWebForm))->ShowLocationListFriendInMap(
				listFriendFollowing);
		SetStateToButton(false, false, false, false);
	}
		break;
	case ID_SOFTKEY_BACK:

		pFormManager->SetCurrentForm(TwitterForm::GetFormId());
		pMySnsGatewayManager->RequestActivities();
		__pFollowerList->RemoveAllItems();
		SetStateToButton(false, false, false, false);
		break;
	case ID_SOFTKEY_XEMFRIENDINMAP: {
		HienThiViTriMotBanBe();

	}
		break;
	default:
		break;
	}

}
void MyFollowingForm::HienThiViTriMotBanBe() {
	FormManager *pFormManager = null;
	Form *pTwitterForm = null;
	Form *pReplyForm = null;
	Form *pWebForm = null;
	FormManager::GetInstance(pFormManager);
	pFormManager->GetForm(TwitterForm::GetFormId(), pTwitterForm);
	pFormManager->GetForm(TwitterReplyForm::GetFormId(), pReplyForm);
	pFormManager->GetForm(WebForm::GetFormId(), pWebForm);
	MySnsGatewayManager
			*pMySnsGatewayManager =
					(static_cast<TwitterForm*> (pTwitterForm))->GetSnsGatewayTwitterForm();

	SnsProfile *snsProfile = pMySnsGatewayManager->GetSnsProfileByIndex(
			indexSelectedInList);
	if (snsProfile == null) {
		ThongBaoLoi("Việc hiển thị vị trí bạn bè thất bại");
	} else if (snsProfile != null) {

		String location;
		SnsStatusText statusText;
		String note;
		DateTime updateTime;
		snsProfile->GetValue(SNS_PROFILE_PID_LOCATION, location);
		statusText = snsProfile->GetStatusText();
		note = statusText.GetStatusText();
		updateTime = statusText.GetUpdateTime();
		String urlPhoto;
		snsProfile->GetValue(SNS_PROFILE_PID_PHOTO_URL, urlPhoto);
		if (location != null && location.GetLength() > 0) {
			pFormManager->SetCurrentForm(WebForm::GetFormId());
			(static_cast<WebForm*> (pWebForm))->ShowLocationFriendInMap(
					location, note, updateTime.ToString(), urlPhoto);
			SetStateToButton(false, false, false, false);
		} else {
			ThongBaoLoi("Việc hiển thị vị trí bạn bè thất bại");
		}
	}

}
void MyFollowingForm::ThongBaoLoi(String value) {
	MessageBox msg;
	msg.Construct("Chào bạn ", value, MSGBOX_STYLE_OK, 3000);
	int i = 0;
	msg.ShowAndWait(i);
}
void MyFollowingForm::AddFollowingList(IList *pBuddyProfileList) {
	indexSelectedInList = 0;
	listFriendFollowing = new ArrayList();
	listFriendFollowing = pBuddyProfileList;
	__pFollowerList->RemoveAllItems();

	if (pBuddyProfileList->GetCount() == 0) {
		ThongBaoLoi("Việc lấy danh sách bạn bè thất bại");
		return;
	} else {
		SnsProfile* pProfile = null;
		String buddyUserName;
		for (int i = 0; i < pBuddyProfileList->GetCount(); i++) {
			pProfile = static_cast<SnsProfile*> (pBuddyProfileList->GetAt(i));
			pProfile->GetValue(SNS_PROFILE_PID_USER_NAME, buddyUserName);
			Bitmap *pBitmapNormal = GetBitmap(i);
			__pFollowerList->AddItem(&buddyUserName,
					&pProfile->GetStatusText().GetStatusText(), pBitmapNormal,
					null, i);
		}
		indexDecodeUrlCurrent = 0;
		DecodeUrlImage();
	}
	__pFollowerList->RequestRedraw(true);
	SetStateToButton(true, true, true, true);
	this->RequestRedraw(true);
}
void MyFollowingForm::DecodeUrlImage() {
	if (indexDecodeUrlCurrent >= listFriendFollowing->GetCount()) {
		AppLog("Thoat ra khoi ham yeu cau hinh anh");
		return;
	}
	SnsProfile* pProfile = null;
	pProfile = static_cast<SnsProfile*> (listFriendFollowing->GetAt(
			indexDecodeUrlCurrent));
	String urlPhoto;
	pProfile->GetValue(SNS_PROFILE_PID_PHOTO_URL, urlPhoto);
	Osp::Graphics::Bitmap * bitmap =
			static_cast<Osp::Graphics::Bitmap*> (__pPicturesCache.GetValue(
					*new String(urlPhoto)));
	if (bitmap == null) {
		Osp::Base::Utility::Uri uri;
		uri.SetUri(urlPhoto);
		AppLog("%S",urlPhoto.GetPointer());
		Osp::Media::Image* __pImage = new Osp::Media::Image();
		__pImage->Construct();
		result r = __pImage->DecodeUrl(uri,
				Osp::Graphics::BITMAP_PIXEL_FORMAT_ARGB8888, 200, 200,
				requestId, *this, 10000);
		if (IsFailed(r)) {

			indexDecodeUrlCurrent++;
			DecodeUrlImage();
		}

	}
	//else
					//{
					/*	AppLog("Image found in cache (do not download it again)");
					 __pLabelMyPicture->SetText(L"");
					 __pLabelMyPicture->SetBackgroundBitmap(*bitmap);
					 *///}
					//__pLabelMyPicture->RequestRedraw(true);

				}
void MyFollowingForm::OnItemStateChanged(const Control& source, int index,
		int itemId, Osp::Ui::ItemStatus status) {
	if (index >= 0) {
		indexSelectedInList = index;
		AppLog("Vị trí :%d", index);
	}
}

Bitmap*
MyFollowingForm::GetBitmap(int i) {
	String fullname(L"/Res/imgPlace/Twitter");
	int tenFile=i%8+1;
	fullname.Append(tenFile);
	fullname.Append(".jpg");
	//AppLog("Name:%S", fullname.GetPointer());
			bool IsTonTai=File::IsFileExist(fullname);
			if(IsTonTai==true)
			{
				Bitmap* pBitmap = null;
				Image* pImage = new Image();
				//	AppLog("Get bitmap:%S", fullname.GetPointer());
				pImage->Construct();
				if(fullname.EndsWith(L"jpg"))
				{
					pBitmap = pImage->DecodeN(fullname,BITMAP_PIXEL_FORMAT_RGB565);
		}
		else if(fullname.EndsWith(L"bmp"))
		{
			pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_RGB565);
		}
		else if(fullname.EndsWith(L"png"))
		{
			pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_ARGB8888);
		}
		else if (fullname.EndsWith(L"gif"))
		{
			pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_RGB565);
		}
		delete pImage;

		return pBitmap;
	}
	return null;
}
int MyFollowingForm::GetIndecSelectInList() {
	return indexSelectedInList;
}
Bitmap*
MyFollowingForm::GetBitmapN(const Osp::Base::String& name) {
	Bitmap* pBitmap = null;
	Image* pImage = new Image();
	String fullname(L"/Res/imgPlace/");
	fullname.Append(name);
	//	AppLog("Get bitmap:%S", fullname.GetPointer());
	pImage->Construct();
	if(fullname.EndsWith(L"jpg"))
	{
		pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_RGB565);
	}
	else if(fullname.EndsWith(L"bmp"))
	{
		pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_RGB565);
	}
	else if(fullname.EndsWith(L"png"))
	{
		pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_ARGB8888);
	}
	else if (fullname.EndsWith(L"gif"))
	{
		pBitmap = pImage->DecodeN(fullname, BITMAP_PIXEL_FORMAT_RGB565);
	}
	delete pImage;
	return pBitmap;
}
void MyFollowingForm::OnImageDecodeUrlReceived(RequestId reqId,
		Osp::Graphics::Bitmap* pBitmap, result r,
		const Osp::Base::String errorCode, const Osp::Base::String errorMessage) {
	if (r == E_SUCCESS) {
		SnsProfile* pProfile = null;
		pProfile = static_cast<SnsProfile*> (listFriendFollowing->GetAt(
				indexDecodeUrlCurrent));
		String buddyUserName;
		pProfile->GetValue(SNS_PROFILE_PID_USER_NAME, buddyUserName);
		__pFollowerList->SetItemAt(indexDecodeUrlCurrent, &buddyUserName,
				&pProfile->GetStatusText().GetStatusText(), pBitmap, null,
				indexDecodeUrlCurrent);
		__pFollowerList->RequestRedraw();
		indexDecodeUrlCurrent++;
		DecodeUrlImage();
		//__pPicturesCache.Add(*new String("MyUniqueKey"), *pBitmap);
		/*AppLog("Image %S downloaded (%S, %S)", Long::ToString(reqId).GetPointer(), errorCode.GetPointer(), errorMessage.GetPointer());
		 if (__pLabelMyPicture != null) {
		 __pLabelMyPicture->SetText(L"");
		 __pLabelMyPicture->SetBackgroundBitmap(*pBitmap);
		 }*/

	}
	/* else
	 {
	 __pLabelMyPicture->SetText(L"Downloading failed");
	 }
	 __pLabelMyPicture->RequestRedraw(true);
	 */}

